<?php
/**
 * SettingRepo.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-08-22 15:56:08
 * @modified    2023-08-22 15:56:08
 *
 */

namespace App\Repositories;

use App\Models\DeptModel;
use App\Models\Setting;
use App\Models\UserModel;
use Illuminate\Support\Str;

class SettingRepo
{
    const KEY_PB_ENGINEER = 'pb_engineer'; // 生产基地品质工程师
    const CODE_PB_GROUP = 'pb_base'; // 生产基地

    public static function getAll()
    {
        $keys = self::keys();
        if (empty($keys)) {
            return [];
        }
        $results = [];
        foreach ($keys as $key) {
            $item = Setting::byKey($key)->first();
            if (empty($item)) {
                $results[$key] = [
                    'serialized' => 0,
                    'value' => ''
                ];
                continue;
            }
            $serialized = $item->serialized;
            $itemValue = $item->value;
            if ($serialized) {
                $itemValue = json_decode($itemValue, true);
            }
            $functionName = "get" . ucfirst(Str::camel($key) . "Item");
            $itemValue = self::$functionName($itemValue);
            $results[$key] = [
                'serialized' => $serialized,
                'value' => $itemValue
            ];
        }
        return $results;
    }

    private static function getPbEngineerItem($item)
    {
        $results = [];
        foreach ($item as $one) {
            $deptId = $one['dept_id'] ?? 0;
            $userId = $one['user_id'] ?? 0;
            $deptName = DeptModel::find($deptId)->name ?? '';
            $userName = UserModel::find($userId)->realname ?? '';
            $one['dept_name'] = $deptName;
            $one['user_name'] = $userName;
            $results[] = $one;
        }
        return $results;
    }

    public static function keys()
    {
        return [
            self::KEY_PB_ENGINEER
        ];
    }

    public static function getDataByKey($key)
    {
        $data = Setting::query()
            ->where('key', $key)
            ->first();
        if (empty($data)) {
            return;
        }
        $value = $data->value;
        $serialized = self::serializedValue($key);
        if ($serialized) {
            $value = json_decode($value, true);
        }
        return $value;
    }

    private static function serializedValue($key)
    {
        $groupKeys = self::groupKeys();
        $groupKeys = $groupKeys['groups'];
        $serialized = false;
        foreach ($groupKeys as $groupKey) {
            $items = $groupKey['items'];
            foreach ($items as $item) {
                $currentKey = $item['key'];
                if ($key == $currentKey && $item['serialized']) {
                    $serialized = true;
                    break;
                }
            }
        }
        return $serialized;
    }

    public static function groupKeys()
    {
        return [
            'keys' => self::keys(),
            'groups' => [
                [
                    'key' => self::CODE_PB_GROUP,
                    'title' => '生产基地',
                    'items' => [
                        [
                            'key' => self::KEY_PB_ENGINEER,
                            'title' => '品质工程师',
                            'serialized' => 1,
                            'item_keys' => [
                                ['key' => 'dept_id', 'title' => '所属部门'],
                                ['key' => 'user_id', 'title' => '工程师'],
                            ]
                        ]
                    ]
                ]
            ]
        ];
    }

    public static function modify()
    {
        $data = request()->getContent();
        $settingData = json_decode($data, true);
        if (empty($settingData)) {
            return;
        }
        foreach ($settingData as $key => $value) {
            $serialized = 0;
            if (is_array($value)) {
                $serialized = 1;
                $value = json_encode($value);
            }
            $itemSetting = Setting::byKey($key)->first();
            if (empty($itemSetting)) {
                $itemSetting = new Setting();
            }
            $itemSetting->key = $key;
            $itemSetting->value = $value;
            $itemSetting->serialized = $serialized;
            $itemSetting->saveOrFail();
        }
    }
}